package com.bestcem.xm.wallet.grpc.client;

import com.bestcem.bp.xm.user.grpc.v1.services.GetOrgByIdOrCodeRequest;
import com.bestcem.bp.xm.user.grpc.v1.services.GetOrgByIdOrCodeResponse;
import com.bestcem.bp.xm.user.grpc.v1.services.OrgServiceGrpc;
import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.wallet.grpc.client.converter.WalletUserGrpcConvert;
import com.bestcem.xm.wallet.grpc.client.dto.OrganizationDTO;
import com.zy.dp.proto.base.v1.Code;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 企业钱包用户服务
 *
 * @author qiongyu.cui <qiongyu.cui@idiaoyan.com>
 * @version v1.0
 * @date 2022/5/13 17:28
 */
@Slf4j
@Service(value = "walletBaseUserGrpcService")
public class WalletBaseUserGrpcService {

    @GrpcClient(GrpcClientNames.DS_USER)
    private OrgServiceGrpc.OrgServiceBlockingStub stub;

    @Resource
    private WalletUserGrpcConvert walletUserGrpcConvert;

    /**
     * 根据公司id查询公司信息
     *
     * @param orgId 公司id
     * @return com.bestcem.xm.wallet.grpc.client.dto.OrganizationDTO
     * @author cuiqiongyu <qiongyu.cui@idiaoyan.cn>
     * @date 2022/05/13 17:50
     */
    public OrganizationDTO getOrganization(String orgId) {
        if (StringUtils.isBlank(orgId)) {
            return null;
        }
        // 组装请求参数
        GetOrgByIdOrCodeRequest request = GetOrgByIdOrCodeRequest.newBuilder().setId(orgId).build();
        GetOrgByIdOrCodeResponse response = null;
        try {
            // 开始查询公司信息
            response = stub.getOrgByIdOrCode(request);
        } catch (Exception e) {
            log.error("根据公司id查询公司信息失败", e);
            return null;
        }
        // 校验检查结果
        if (Code.ERROR_VALUE == response.getStatus().getCodeValue()) {
            log.error("根据公司id查询公司信息失败：dto:{} orgId:{}", response.getStatus().getMessage(), orgId);
            return null;
        }
        return walletUserGrpcConvert.orgGrpc2Dto(response.getOrg());
    }

}
